<template>
  <div class="also">
    <div class="products-slider">
      <div class="products-container-wrapper">
        <!-- <button class="nav-button prev" @click="scrollLeft" v-show="!isAtStart && !loading" :aria-label="isAtStart ? 'No previous products' : 'Previous product'">
          <left-outlined style="font-size: 12px; color: #333;" />
        </button> -->
        
        <!-- 骨架屏加载效果 -->
        <div v-if="loading" class="products-container skeleton-container">
          <div v-for="i in 8" :key="i" class="product-card skeleton-card">
            <div class="skeleton-image"></div>
            <div class="skeleton-info">
              <div class="skeleton-name"></div>
              <div class="skeleton-price"></div>
            </div>
          </div>
        </div>
        
        <!-- 实际内容 -->
        <div v-else class="products-container" ref="container" @scroll="handleScroll">
          <div v-for="product in relatedGoods" :key="product.id"  class="product-card">
            <div class="product-image">
                <a :href="`/product/${product.url}.html`" :title="product.name" target="_self" >
                  <img 
                    :src="product.images[0]" 
                    :alt="product.name" 
                    @mouseenter="showSecondImage($event, product.images)"
                    @mouseleave="showFirstImage($event, product.images[0])"
                  />
                </a>
                <a-button class="add-btn" v-if="!open" @click="addCart(product)">Add+</a-button>
                <a-button class="add-btn" v-else  @click="handleBuy">Add-</a-button>
            </div>
            <div class="product-info">
              <h3 class="product-name">{{ product.name }}</h3>
              <div class="price">{{ currencyStore.currentCurrency.unit }}{{ proxy.$ConvertPrice(product.min_price || product.price) }}</div>
            </div>
          </div>
        </div>
        
        <!-- <button class="nav-button next" @click="scrollRight" v-show="!isAtEnd && !loading" :aria-label="isAtEnd ? 'No next products' : 'Next product'">
          <right-outlined style="font-size: 12px; color: #333;" />
        </button> -->
      </div>
    </div>
  </div>
  <a-modal v-model:open="open" width="1200px" title="Product Details" :footer="null">
    <ProductDetail.default v-if="open && goodId" :goodId="goodId" @buy="handleBuy" />
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance, watch, watchEffect } from 'vue';
import { LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useCurrencyStore } from '../../../store/currency';
import * as ProductDetail from '@/components/ProductDetail.vue';
const { proxy } = getCurrentInstance()
interface ProductType {
  id: string | number;
  name: string;
  // max_price: string | number;
  min_price: string | number;
  price: string | number;
  images: string[];
  url: string;
}

interface BuyData {
  productId?: string | number;
  quantity?: number;
  [key: string]: any;
}

const open = ref<boolean>(false);
const goodId = ref<string | null>(null);
const currencyStore = useCurrencyStore();
const container = ref<HTMLElement | null>(null);
const isAtStart = ref(false);
const isAtEnd = ref(true);
const loading = ref(true); // 添加加载状态变量
const instance = getCurrentInstance();

const props = defineProps({
  relatedGoods: {
    type: Array as () => ProductType[],
    required: true,
  },
  imageWidth: {
    type: Number,
    default: 130
  },
  imageHeight: {
    type: Number,
    default: 173
  }
});

// 监听relatedGoods数据变化
watch(() => props.relatedGoods, (newVal) => {
  if (newVal && newVal.length > 0) {
    loading.value = false;
    // 在数据加载完成后更新滚动状态
    setTimeout(() => {
      if (container.value) {
        handleScroll();
      }
    }, 100);
  }
}, { immediate: true });

const goProductDetails = (product: ProductType) => {
  window.location.href = `/product/${product.url}.html`;
}

const handleScroll = () => {
  if (container.value) {
    const { scrollLeft, scrollWidth, clientWidth } = container.value;
    isAtStart.value = scrollLeft === 0;
    isAtEnd.value = Math.abs(scrollWidth - clientWidth - scrollLeft) < 1;
  }
};



const addCart = (product: ProductType) => {
  // 防止穿透点击
  if (open.value) {
    return;
  }
  // 打开购买弹窗
  open.value = true;
  // console.log("product.id",product.id)
  goodId.value = product.id;
}
// 处理购买按钮点击
const handleBuy = (data?: BuyData) => {
  message.success('The product has been successfully added to the cart, please go to the cart for settlement');
  open.value = false;
};
// const scrollLeft = () => {
//   if (container.value) {
//     container.value.scrollBy({
//       left: -92,
//       behavior: 'smooth'
//     });
//   }
// };

// const scrollRight = () => {
//   if (container.value) {
//     container.value.scrollBy({
//       left: 92,
//       behavior: 'smooth'
//     });
//   }
// };

onMounted(() => {
  // 如果数据已经存在，则直接关闭加载状态
  if (props.relatedGoods && props.relatedGoods.length > 0) {
    loading.value = false;
    setTimeout(() => {
      if (container.value) {
        handleScroll();
      }
    }, 100);
  } else {
    // 如果初始数据不存在，等待一段时间后关闭骨架屏（这里作为备用方案）
    setTimeout(() => {
      loading.value = false;
    }, 1500);
  }
});

const showSecondImage = (event: MouseEvent, images: string[]) => {
  if (images.length > 1) {
    const imgElement = event.target as HTMLImageElement;
    imgElement.src = images[1];
  }
};

const showFirstImage = (event: MouseEvent, firstImage: string) => {
  const imgElement = event.target as HTMLImageElement;
  imgElement.src = firstImage;
};
</script>

<style lang="scss" scoped>
.also {
  padding: 10px 0;
  margin: 0 auto;

  .products-slider {
    position: relative;

    .products-container-wrapper {
      position: relative;
      display: flex;
      align-items: flex-start;
      gap: 10px;
      .nav-button {
        background: white;
        border: 1px solid #e8e8e8;
        width: 25px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.3s;
        position: absolute;
        top: 45px;
        z-index: 1;

        &:hover {
          background: #f5f5f5;
        }

        &.prev {
          left: 0;
        }

        &.next {
          right: 0;
        }
      }

      .products-container {
        flex: 1;
        display: flex;
        gap: 10px;
        overflow-x: auto;
        scroll-behavior: smooth;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* IE and Edge */

        &::-webkit-scrollbar {
          display: none; /* Chrome, Safari, Opera */
        }
      }
      
      /* 骨架屏样式 */
      .skeleton-container {
        padding: 10px 30px;
      }
      
      .skeleton-card {
        flex: 0 0 92px;
        
        .skeleton-image {
          width: 130px;
          height: 173px;
          background-color: #f5f5f5;
          border-radius: 4px;
          margin-bottom: 8px;
          animation: skeleton-pulse 1.4s ease-in-out infinite;
        }
        
        .skeleton-info {
          .skeleton-name {
            width: 80%;
            height: 10px;
            background-color: #f5f5f5;
            border-radius: 2px;
            margin-bottom: 8px;
            animation: skeleton-pulse 1.4s ease-in-out infinite;
          }
          
          .skeleton-price {
            width: 60%;
            height: 10px;
            background-color: #f5f5f5;
            border-radius: 2px;
            animation: skeleton-pulse 1.4s ease-in-out infinite;
          }
        }
      }
    }

    .product-card {
      flex: 0 0 92px;
      cursor: pointer;

      .product-image {
        width: v-bind('props.imageWidth + "px"');
        height: v-bind('props.imageHeight + "px"');
        overflow: hidden;
        margin-bottom: 8px;
        position: relative;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s ease;
        }

        &:hover img {
          transform: scale(1.05);
        }
      
      }
     
     
      .product-info {
        .brand {
          font-size: 10px;
          color: #666;
          margin-bottom: 4px;
        }

        .product-name {
          font-size: 12px;
          font-weight: 600;
          margin: 0 0 4px 0;
          line-height: 1.4;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .price {
          font-size: 14px;
          // font-weight: 900;
        }
      }
    }
  }
}
:deep(.ant-btn) {
  font-size: 14px;
  height: 32px;
  padding: 0px 10px; 
  border-radius: 6px;
}
.add-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
  width: 50px;
  height: 30px;
  border: none;
  border:1px solid #ccc;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 900;
}
/* 骨架屏动画 */
@keyframes skeleton-pulse {
  0% {
    background-color: #f5f5f5;
  }
  50% {
    background-color: #ebebeb;
  }
  100% {
    background-color: #f5f5f5;
  }
}
</style>